package com.albert.order.delayqueue;

import com.albert.order.entry.DelayOrderTask;
import com.albert.order.entry.OrderInfo;
import com.albert.order.entry.OrderTypeEnum;
import com.albert.order.service.DelayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.concurrent.DelayQueue;

/**
 * 限时任务类
 *
 * @author yangjunwei
 * @date 2021/7/3 上午2:06
 */
@Component
@Slf4j
public class DelayQueueProcessor {

    @Resource
    DelayOrderService delayOrderService;

    private static DelayQueue<DelayOrderTask> delayOrderQueue = new DelayQueue<>();

    public void orderDelay(OrderInfo orderInfo) {
        //获取订单过期时间
        Long timeLimitValue = OrderTypeEnum.getTimeLimitValueByOrderType(orderInfo.getOrderType());
        DelayOrderTask delayOrderTask = new DelayOrderTask(orderInfo.getId(), timeLimitValue);
        //添加延时队列
        delayOrderQueue.put(delayOrderTask);
    }

    /**
     * 延时队列取任务
     */
    private class TaskOrder implements Runnable {

        @Override
        public void run() {
            log.info("-------开始监听延时队列--------");
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    //从延时队列取任务
                    DelayOrderTask delayOrderTask = delayOrderQueue.take();
                    //对到期订单，进行检查
                    delayOrderService.fillDelayOrder(delayOrderTask.getOrderId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 处理任务的线程
     */
    private Thread thread;

    @PostConstruct
    public void init() {
        log.info("-------start thread------ 开启任务线程");
        thread = new Thread(new TaskOrder());
        thread.start();
    }

    @PreDestroy
    public void destory() {
        thread.interrupt();
    }


}
